package com.ms.p2p.scheduled;


import com.ms.p2p.entity.account.Withdraw;
import com.ms.p2p.provider.RedPacketProvider;
import com.ms.p2p.service.impl.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xing_ on 2017/6/10.
 */
@Component
public class ScheduledJob {

    protected static Logger logger = Logger.getLogger(ScheduledJob.class);

    @Autowired
    private YuEbaoServiceImpl yueBaoService;

    @Autowired
    private MemberWithDrawServiceImpl withDrawService;

    @Autowired
    private PayMethodValueServiceImpl payMethodValueService;


    @Autowired
    private LoanServiceImpl loanService;


    @Autowired
    private RedPacketServiceImpl redPacketService;
    /**
     * 计算活期宝收益保存数据库
     */
    @Scheduled(cron="0 0 1 * * ?")
    public void IncomeDistribution() {
        try {
            yueBaoService.IncomeDistribution();
        } catch (Exception e) {
            logger.error("计算活期宝收益异常", e);
        }

    }


    /**
     * 每天0点
     */
    @Scheduled(cron="0 0 0 * * ?")
    public void overDueRedPacket() {
        try {
            redPacketService.overDue();
        } catch (Exception e) {
            logger.error("红包处理异常", e);
        }

    }
    /**
     * 预发标处理
     *
     * */
    @Scheduled(cron="0 0/1 *  * * ?")
    public void AutoLoan() {
            loanService.autoLoan();

    }

//    /**
//     * 修改特价产品到期状态
//     */
//    @Scheduled(cron="0 0/1 *  * * ?")
//    public void cashQuery() throws IllegalAccessException, IntrospectionException, InvocationTargetException {
//
//        List<Map<String,Object>> cashList = withDrawService.findList("0",null,null,null,null);
//        StringBuffer cashno = new StringBuffer();
//        int i=0;
//        for(Map<String,Object> cond : cashList){
//            i=i+1;
//            if (i == cashList.size()) {
//                cashno.append(cond.get("trade_no"));
//            } else {
//                cashno.append(cond.get("trade_no")).append(",");
//            }
//
//        }
//        String ver = "1.0";
//        String busicd = "AP01";
//        String orderno = cashno.toString();
//        if (orderno !=null && !orderno.equals("")) {
//
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            String endstr = sdf.format(new Date());
//            Calendar startdt_c = Calendar.getInstance();
//            startdt_c.roll(Calendar.DATE, -7);//日期回滚7天
//            String startdt = sdf.format(startdt_c.getTime());
//            String enddt = endstr;
//            String transst = "";
//            String xml = "<qrytransreq><ver>" + ver + "</ver><orderno>" + orderno + "</orderno><busicd>" + busicd + "</busicd><startdt>" + startdt + "</startdt><enddt>" + enddt + "</enddt><transst>" + transst + "</transst></qrytransreq>";
//            String reqType = "qrytransreq";
//            List list = new ArrayList();
//            String[] nv1 = { "merid", payMethodValueService.findByName("fuyou.mchnt_cd").getParamValue()};
//            String[] nv2 = { "xml", xml };
//            list.add(nv1);
//            list.add(nv2);
//            String[] nv3 = { "reqtype", reqType };
//            list.add(nv3);
//            String url = "https://fht.fuiou.com/req.do";
//            String macSource = payMethodValueService.findByName("fuyou.mchnt_cd").getParamValue() + "|" +payMethodValueService.findByName("fuyou.b2ckey").getParamValue() + "|" + reqType + "|" + xml;
//            String mac = MD5Util.encode(macSource, "UTF-8").toUpperCase();
//            String[] nv4 = { "mac", mac };
//            list.add(nv4);
//            String nvPairs = HttpClientHelper.getNvPairs(list, "UTF-8");
//            String outStr = HttpClientHelper.doHttp(url, "POST", "UTF-8", nvPairs, (String)props.get("timeout"));
//            System.out.println(outStr);
//            List<CashBean> cashBeanList = new ArrayList<CashBean>();
//            String retRes = getNode(outStr,"ret");
//            if (StringUtils.isNotEmpty(retRes) && retRes.equals("000000")) {
//
//                String[] resArray = outStr.split("</trans>");
//                for (int n=0;n<resArray.length;n++) {
//                    CashBean cashBeanTemp = new CashBean();
//                    String temp = resArray[n];
//                    String ordernoT = getNode(temp,"orderno");
//                    String stateT = getNode(temp,"state");
//                    cashBeanTemp.setOrderno(ordernoT);
//                    cashBeanTemp.setState(stateT);
//                    cashBeanList.add(cashBeanTemp);
//                }
//                for (CashBean temp: cashBeanList) {
//                    AccountCash cashTemp = cashService.findByTradeNo(temp.getOrderno());
//                    if (cashTemp !=null && cashTemp.getStatus().equals(0)) {
//                        if (temp.getState().equals("1")) {
//                            accountService.payOutForFrozen(cashTemp.getTotal(),cashTemp.getUser_id(),"恭喜您，您的提现申请审核通过，申请提现金额￥" + cashTemp.getTotal() + "，到账金额￥" + cashTemp.getCredited()
//                                    ,"127.0.0.1","withdraw_success");
//                            cashTemp.setStatus(1);
//                        } else if (temp.getState().equals("2")){
//                            cashTemp.setStatus(-1);
//                            accountService.thaw(cashTemp.getTotal(),cashTemp.getUser_id(),"抱歉 提现失败","127.0.0.1","withdrawal_cancel");
//                            Account account = accountService.findByUserId(cashTemp.getUser_id());
//                            int oldTimes = account.getTimes();
//                            if(cashTemp.getFee().compareTo(BigDecimal.ZERO)==0){
//                                accountLogService.updateTimes(++oldTimes, cashTemp.getUser_id());
//                            }
//
//                        }
//                        cashService.update(BeanMapUtil.bean2Map(cashTemp));
//                    }
//                }
//            }
//        }
//
//    }
//
//    public static String getNode(String plain, String nodename) {
//        if(plain.indexOf("<" + nodename + ">")<0) return "";
//        return plain.substring(plain.indexOf("<" + nodename + ">")
//                + nodename.length() + 2, plain.indexOf("</" + nodename + ">"));
//    }

    /**
     * 流标处理
     * 每10分钟流一次标
     *
     * */
    @Scheduled(cron="0 0/10 *  * * ?")
    public void AutoCaculateLoan() {
        loanService.autoCaculateLoan();

    }


}
